package com.yjd.pub.settlement.service;

import com.yjd.comm.base.dao.IBaseDao;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.service.impl.BaseServiceImpl;
import com.yjd.comm.funds.enums.FundsIncomeEnum;
import com.yjd.comm.merchant.enums.MerchantFundRefTabEnum;
import com.yjd.comm.merchant.enums.MerchantFundsTypeEnum;
import com.yjd.comm.merchant.model.MerchantFundsModel;
import com.yjd.comm.merchant.service.IMerchantFundsDataService;
import com.yjd.comm.merchant.service.IMerchantFundsService;
import com.yjd.comm.settlement.model.ClearDayMerchantModel;
import com.yjd.comm.settlement.service.IClearDayMerchantService;
import com.yjd.comm.util.ArithUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.pub.settlement.dao.IClearDayMerchantDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <b>description</b>：商户日结业务实现<br>
 * <b>time</b>：2017-08-11 17:28:17 <br>
 * <b>author</b>：  yangchangyan@yijiedai.com
 */
@Service("clearDayMerchantService")
public class ClearDayMerchantServiceImpl extends BaseServiceImpl implements IClearDayMerchantService {

	/**
	 * 插入
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public ClearDayMerchantModel insert(ClearDayMerchantModel model) throws Exception {
		return this.clearDayMerchantDao.insertModel(model, true);
	}

	/**
	 * 更新
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public int update(ClearDayMerchantModel model) throws Exception {
		return this.clearDayMerchantDao.updateModel(model, true);
	}

	/**
	 * 根据id删除
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public int delete(long id) throws Exception {
		Map<Object, Object> paramMap = new HashMap<Object, Object>();
		paramMap.put("id", id);
		return this.clearDayMerchantDao.deleteModel(paramMap, true);
	}

	/**
	 * 商户结算
	 *
	 * @param org_id
	 * @param settlement_id
	 * @throws Exception
	 */
	@Override
	public void settlement(Long org_id,Long settlement_id) throws Exception {
		if(org_id==null||settlement_id==null){
			FrameUtil.throwBaseException1("参数异常!");
		}

		ClearDayMerchantModel clearDayMerchantModel = clearDayMerchantDao.getModelOne(FrameUtil.newHashMap("id",settlement_id,"org_id",org_id), true);
		if(clearDayMerchantModel==null){
			FrameUtil.throwBaseException1("您选择的结算不存在或不属于你的机构！");
		}

		Long currtime = FrameUtil.getTime(null);
		ClearDayMerchantModel clearDayModel = new ClearDayMerchantModel();
		clearDayModel.setId(settlement_id);
		clearDayModel.setWhere_status(0);
		clearDayModel.setStatus(1);
		clearDayModel.setConfirm_time(currtime);

		if(clearDayMerchantDao.updateModel(clearDayModel,true)!=1){
			FrameUtil.throwBaseException1("结算失败，请重试！");
		}

		//结算单确认 资金账户变动：- 待收回收累计金额  + 累计已还款金额 +vip订单累计管理费 +vip订单累计罚息金额
		// + vip订单逾期累计管理费 +vip订单累计利息 + 账户可用余额

	    MerchantFundsModel merchantFundsModel = merchantFundsService.getModelById(org_id, DbWREnums.WRITE);
		if(merchantFundsModel==null){
			FrameUtil.throwBaseException1("资金账户不存在");
		}

		Double currBalance = merchantFundsModel.getAvailable();

		//资金流水 当日订单收入金额
		if(clearDayMerchantModel.getLoan_price().doubleValue()>0){
			currBalance = ArithUtil.add(currBalance,clearDayMerchantModel.getLoan_price());
			merchantFundsDataService.insertFundsData(org_id,clearDayMerchantModel.getLoan_price(),currBalance, FundsIncomeEnum.ADD,
					MerchantFundsTypeEnum.ORDER_IN,clearDayMerchantModel.getId().toString(), MerchantFundRefTabEnum.MFQ_CLEAR_DAY_MERCHANT,currtime);
		}

        //资金流水 还款罚息金额
        if(clearDayMerchantModel.getOverdue_price().doubleValue()>0){
            currBalance = ArithUtil.add(currBalance,clearDayMerchantModel.getOverdue_price());
            merchantFundsDataService.insertFundsData(org_id,clearDayMerchantModel.getOverdue_price(),currBalance, FundsIncomeEnum.ADD,
                    MerchantFundsTypeEnum.OVERDUE,clearDayMerchantModel.getId().toString(), MerchantFundRefTabEnum.MFQ_CLEAR_DAY_MERCHANT,currtime);
        }

        //资金流水 还款金额
        if(clearDayMerchantModel.getRepayment_price().doubleValue()>0){
            currBalance = ArithUtil.add(currBalance,clearDayMerchantModel.getRepayment_price());
            merchantFundsDataService.insertFundsData(org_id,clearDayMerchantModel.getRepayment_price(),currBalance, FundsIncomeEnum.ADD,
                    MerchantFundsTypeEnum.REPAYMENT,clearDayMerchantModel.getId().toString(), MerchantFundRefTabEnum.MFQ_CLEAR_DAY_MERCHANT,currtime);
        }


        //资金流水 当日退单金额
		if(clearDayMerchantModel.getBorrow_price().doubleValue()>0){
			currBalance = ArithUtil.sub(currBalance,clearDayMerchantModel.getBorrow_price());
			merchantFundsDataService.insertFundsData(org_id,clearDayMerchantModel.getBorrow_price(),currBalance, FundsIncomeEnum.REDUCE,
					MerchantFundsTypeEnum.ORDER_OUT,clearDayMerchantModel.getId().toString(), MerchantFundRefTabEnum.MFQ_CLEAR_DAY_MERCHANT,currtime);
		}


		//资金流水 平台利息分成手续费
		if(clearDayMerchantModel.getManage().doubleValue()>0){
			currBalance = ArithUtil.sub(currBalance,clearDayMerchantModel.getManage());
			merchantFundsDataService.insertFundsData(org_id,clearDayMerchantModel.getManage(),currBalance, FundsIncomeEnum.REDUCE,
					MerchantFundsTypeEnum.SERVICE_FEE,clearDayMerchantModel.getId().toString(), MerchantFundRefTabEnum.MFQ_CLEAR_DAY_MERCHANT,currtime);
		}

		//资金流水 还款罚息利润分成
		if(clearDayMerchantModel.getManage_overdue().doubleValue()>0){
			currBalance = ArithUtil.sub(currBalance,clearDayMerchantModel.getManage_overdue());
			merchantFundsDataService.insertFundsData(org_id,clearDayMerchantModel.getManage_overdue(),currBalance, FundsIncomeEnum.REDUCE,
					MerchantFundsTypeEnum.OVERDUE_FEE,clearDayMerchantModel.getId().toString(), MerchantFundRefTabEnum.MFQ_CLEAR_DAY_MERCHANT,currtime);
		}

		//记录还款清算表
		Map updateMFundsParam = FrameUtil.newHashMap();
		updateMFundsParam.put("update_time", currtime);
		updateMFundsParam.put("where_version", merchantFundsModel.getVersion());
		updateMFundsParam.put("reduce_recovery_price", clearDayMerchantModel.getRepayment_price());//减少待回收金额
		updateMFundsParam.put("add_repayment_price",  clearDayMerchantModel.getRepayment_price());//增加已还金额
		updateMFundsParam.put("add_vip_manage", clearDayMerchantModel.getManage());//增加平台管理费
		updateMFundsParam.put("add_vip_interest", clearDayMerchantModel.getInterest_price());//增加已还利息

		if (clearDayMerchantModel.getOverdue_price().doubleValue() > 0) {
			updateMFundsParam.put("add_overdue", clearDayMerchantModel.getOverdue_price());//增加罚息金额
		}
		if (clearDayMerchantModel.getManage_overdue().doubleValue() > 0) {
			updateMFundsParam.put("add_overdue_manage", clearDayMerchantModel.getManage_overdue());//增加平台罚息分润金额
		}

		//计算当日资金账户变动金额
		updateMFundsParam.put("available",currBalance);

		if (merchantFundsService.updataByMap(org_id, updateMFundsParam) != 1) {
			FrameUtil.throwBaseException1("更新商户资金信息失败");
		}

	}

	@Resource
	private IClearDayMerchantDao clearDayMerchantDao;
	@Resource
	private IMerchantFundsService merchantFundsService;

	@Resource
	private IMerchantFundsDataService merchantFundsDataService;

	@Override
	public IBaseDao getBaseDao() {
		return this.clearDayMerchantDao;
	}

}
